package com.bckj.fastboot.core.extra.extpt;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import com.bckj.fastboot.core.extra.stage.StageRepository;
import com.bckj.fastboot.core.util.ByteBuddyProxyFactory;
import com.bckj.fastboot.core.util.SpringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;

@SuppressWarnings("unchecked")
@RequiredArgsConstructor
public class DynamicExtPtGenerator {

    private final StageRepository stageRepository;

    public <T> T generate(ExtPtProfile profile) throws Exception {
        if (profile.getType() == ExtPtProfile.TYPE_PROCESS) {
            ExtPtProcHandler procHandler;
            try {
                procHandler = SpringUtils.getBean(ExtPtProcHandler.class);
            } catch (BeansException e) {
                throw new BusinessException("请配置ExtPtProcHandler");
            }
            return (T) ByteBuddyProxyFactory.createProxy(Class.forName(profile.getInterfaceName()),
                    new DynamicProcExtPtHandler(stageRepository, profile, procHandler));
        }
        return (T) ByteBuddyProxyFactory.createProxy(Class.forName(profile.getInterfaceName()),
                new DynamicExtPtHandler(stageRepository, profile));
    }
}
